from flask import Blueprint, jsonify, request

from app.models.category import CategorySchema
from app.services import category_service

bp = Blueprint('categories', __name__, url_prefix='/categories')

categories_schema = CategorySchema(many=True)
category_schema = CategorySchema()


@bp.route('/')
def get_categories():
    categories = category_service.get_all_categories()

    return jsonify(
        {'code': 1, 'message': '获取图书列表成功', 'data': categories_schema.dump(categories)})


@bp.route('/<int:category_id>')
def get_category(category_id):
    category = category_service.get_category_by_id(category_id)

    return jsonify(
        {'code': 1, 'message': '获取图书详细信息成功', 'data': category_schema.dump(category)})


@bp.route('/', methods=['POST'])
def add_category():
    request_data = request.get_json()

    category_service.add_category(request_data)

    return jsonify({'code': 1, 'message': '添加图书类别成功'})


@bp.route('/<int:category_id>', methods=['DELETE'])
def delete_category(category_id):
    print(f'要删除的类别序号=============================>：{category_id}')

    category_service.delete_category(category_id)

    return jsonify({'code': 1, 'message': '删除类别成功'})


@bp.route('/', methods=['PUT'])
def update_category():
    request_data = request.get_json()

    print(f'获取到的数据：{request_data}')

    category_service.update_category(request_data)

    return jsonify({'code': 1, 'message': '修改类别信息成功'})
